pub use jwt_simple::Error;

use jwt_simple::prelude::*;
use once_cell::sync::Lazy;
use std::env;

/// 自定义认证信息
#[derive(Serialize, Deserialize)]
pub struct MyClaims {
    pub username: String,
}

/// 密钥
static KEY: Lazy<HS256Key> = Lazy::new(|| {
    let secret = env::var("SECRET").expect("NO `SECRET`");

    HS256Key::from_bytes(secret.as_bytes())
});

pub fn gen(username: String) -> Result<String, Error> {
    let claims = Claims::with_custom_claims(MyClaims { username }, Duration::from_days(3))
        .with_issuer("Personnel-Manager");

    KEY.authenticate(claims)
}

pub fn parse(token: &str) -> Result<MyClaims, Error> {
    KEY.verify_token::<MyClaims>(token, None)
        .map(|claims| claims.custom)
}
